const Koa = require('koa')
const app = new Koa()
const Router = require('koa-router')
let router = new Router()

const mongoose = require('mongoose')
const fs = require('fs')

router.get('/insertBanner', async (ctx) => {
  fs.readFile('./data_json/banner.json', 'utf8', (err, data) => {
    data = JSON.parse(data)
    let saveCount = 0
    const Banner = mongoose.model('Banner')
    data.RECORDS.map((value, index) => {
      console.log(value)
      let newBanner = new Banner(value)
      newBanner
        .save()
        .then(() => {
          saveCount++
          console.log('成功插入' + saveCount)
        })
        .catch((error) => {
          console.log('插入失败:' + error)
        })
    })
  })
  ctx.body = '开始导入数据'
})
router.get('/getBanner', async (ctx) => {
  try {
    const Banner = mongoose.model('Banner')
    let res = await Banner.find().exec()
    ctx.body = {
      data: {
        code: 200,
        message: res,
      },
    }
  } catch (error) {
    console.log(error)
    ctx.body = {
      data: {
        code: 500,
        message: '查询信息失败',
      },
    }
  }
})

module.exports = router
